from django.shortcuts import render
from alldata.tools.w_usersum import obtain_user_shop
from alldata.tools.w_usersum_other import obtain_data
from alldata.tools.w_usersum_create import create_user_excel
from alldata.tools.w_info_excel import create_info_excel
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from datetime import datetime, timedelta
from .models import c_company_jane
from alldata.tools.w_edsum import chart_userdata
from django.core.cache import cache
from alldata.tools.w_other import Mysql, InfoMysql
from tools.w_decorator import performance
from django.contrib.auth.decorators import login_required

import threading
import pymysql
import re
import configparser
import traceback
import json
import queue
#平台数据
q_data = queue.Queue()
mysqlcon = Mysql()
user_shop_return = None
user_shop_excel = None
sum_user_data = None
user_shop_list = None
alldate = None
# cursor = mysqlcon.mysql_con()
date_type_list = ["week_data", "month_data", "year_data"]
chart_class = chart_userdata()

@login_required(login_url='/login')
def userchart(request):
    jane_full_data("One")
    # userchartThree()
    us_return_list = cache.get("jane_list")
    return render(request, 'alldata/user-chart.html', {"jane_name": json.dumps(us_return_list)})


@csrf_exempt
@login_required(login_url='/login')
def userchartOne(request):
    if request.is_ajax():
        if request.method == "POST":
            ucc_org_data, ucc_amp_org, ucc_inc_data, ucc_amp_inc = [],[],[],[]
            try:
                ucc_jane_name = request.POST.get("return_name")
                ucc_date_type = int(request.POST.get("selectdata"))
                ucc_date_serial = request.POST.get("serial_number")
                ucc_t = threading.Thread(target=chart_class.to_obtain_data, args=(ucc_date_type,))
                ucc_t.start()
                ucc_t.join()
                ucc_cache_name = date_type_list[ucc_date_type] + '_' + ucc_date_serial
                ucc_sql_data = cache.get(ucc_cache_name)
                ucc_org_data, ucc_amp_org, ucc_inc_data, ucc_amp_inc = to_deal_data(ucc_sql_data[ucc_jane_name])
            except BaseException as b:
                _log_err = "userchartOne函数异常 --》" + str(b)
                print(_log_err)
            finally:
                return HttpResponse(json.dumps({"org_data":ucc_org_data, "org_amp":ucc_amp_org, "inc_data":ucc_inc_data, "inc_amp":ucc_amp_inc}))

def jane_full_data(jfd_status):
    jfd_id_cache = cache.get("jane_id")
    jfd_jane_cache = cache.get("jane_list")
    jfd_no_jane_list = {}
    jfd_name_list = []
    jfd_return_list = []
    jfd_return_jane_id = {}
    jfd_full_list = []
    if jfd_status == "One" or jfd_id_cache == None or jfd_jane_cache == None:
        full_name_sql = "select companyId, companyName from y_info_company where isUsing = 1 and isDelete = 0 and companyId not in (1,2,3,4,7,8)"
        jfd_jane_list = c_company_jane.objects.values_list('full_name', 'jane_name')
        jfd_full_list = mysqlcon.getAll(full_name_sql)
        for jfd_i in jfd_jane_list:
            jfd_return_list.append(jfd_i[1])
            jfd_name_list.append(jfd_i[0])
            jfd_return_jane_id[jfd_i[1]] = [jfd_n[0] for jfd_n in jfd_full_list if jfd_n[1] == jfd_i[0]][0]
        for jfd_f in jfd_full_list:
            if jfd_f[1] not in jfd_name_list:
                jfd_no_jane_list[jfd_f[0]] = jfd_f[1]
        cache.set("jane_list", jfd_return_list)
        cache.set("jane_id", jfd_return_jane_id)
    elif jfd_status == "Three":
        full_name_sql = "select companyId, companyName from y_info_company where isUsing = 1 and isDelete = 0 and companyId not in (1,2,3,4,7,8)"
        jfd_jane_list = c_company_jane.objects.values_list('full_name', 'jane_name')
        jfd_full_list = mysqlcon.getAll(full_name_sql)
        for jfd_i in jfd_jane_list:
            jfd_name_list.append(jfd_i[0])
        for jfd_f in jfd_full_list:
            if jfd_f[1] not in jfd_name_list:
                jfd_no_jane_list[jfd_f[0]] = jfd_f[1]
    return jfd_no_jane_list

def to_deal_data(tdd_list_data):
    tdd_inc_data = tdd_list_data[1::2]
    tdd_org_data = tdd_list_data[::2]
    tdd_inc_max = max(tdd_inc_data)
    tdd_org_max = max(tdd_org_data)
    tdd_amp_inc = []
    tdd_amp_org = []
    if tdd_org_max > tdd_inc_max:
        c = len(str(tdd_org_max)) - 1
        if c > 0:
            d = 10 ** c
        else:
            d = 10
    else:
        c = len(str(tdd_inc_max)) - 1
        if c > 0:
            d = 10 ** c
        else:
            d = 10
    for tdd_n in range(len(tdd_org_data)):
        tdd_org_data[tdd_n] = -tdd_org_data[tdd_n]
    for tdd_i in tdd_org_data:
        tdd_amp_org.append(-d+tdd_i)
    for tdd_x in tdd_inc_data:
        tdd_amp_inc.append(d+tdd_x)
    return tdd_org_data, tdd_amp_org, tdd_inc_data, tdd_amp_inc

@csrf_exempt
@login_required(login_url='/login')
def userchartTwo(request):
    if request.is_ajax():
        if request.method == "POST":
            uct_jane_name = request.POST.get("return_name")
            uct_date_type = int(request.POST.get("selectdata"))
            uct_date_serial = request.POST.get("serial_number")
            jane_full_data("Two")
            uct_jane_id = cache.get("jane_id")
            uct_t = threading.Thread(target=chart_class.cloth_removal, args=(uct_date_type, uct_date_serial, uct_jane_id[uct_jane_name], uct_jane_id,))
            uct_t.start()
            uct_t.join()
            uct_cache_name = date_type_list[uct_date_type] + '_' + str(uct_jane_id[uct_jane_name]) + '_' + uct_date_serial
            uct_cache_name_sql = date_type_list[uct_date_type] + '_' + str(uct_jane_id[uct_jane_name]) + '_' + uct_date_serial + '_' + 'sql'
            uct_status = True

            while uct_status:
                uct_mog_data = cache.get(uct_cache_name)
                uct_sql_data = cache.get(uct_cache_name_sql)
                if uct_mog_data != None and uct_sql_data != None:
                    uct_status = False
                    print('===============================')
                    print(uct_jane_name, uct_jane_id[uct_jane_name])
                    print(uct_mog_data)
                    print(uct_sql_data)
                    print('===============================')
            uct_x_list,uct_mog_list, uct_sql_list = two_mod_data(uct_date_type, uct_mog_data, uct_sql_data)
            return HttpResponse(json.dumps({"edun_line_x": uct_x_list, "edun_mog_data":uct_mog_list, "edun_sql_data":uct_sql_list}))


def two_mod_data(tmd_id, tmd_mog_data, tmd_sql_data):
    tmd_x_name = ['日','日','月'][tmd_id]
    tmd_x_list = []
    tmd_mod_list = []
    tmd_sql_list = []
    tmd_today = datetime.today()
    tmd_month = int(tmd_today.month)
    if tmd_id == 2:
        tmd_keys = list(tmd_sql_data.keys())
        tmd_keys.sort()
        for tmd_k in tmd_keys:
            if tmd_k >= tmd_month:
                tmd_l = tmd_k - tmd_month
                tmd_sql_list.insert(tmd_l,tmd_sql_data[tmd_k])
                tmd_mod_list.insert(tmd_l,tmd_mog_data[tmd_k])
                tmd_x_list.insert(tmd_l, str(tmd_k) + tmd_x_name)
            else:
                tmd_sql_list.append(tmd_sql_data[tmd_k])
                tmd_mod_list.append(tmd_mog_data[tmd_k])
                tmd_x_list.append(str(tmd_k) + tmd_x_name)
    else:
        tmd_keys = list(tmd_sql_data.keys())
        tmd_keys.sort()
        for tmd_k in tmd_keys:
            tmd_sql_list.append(tmd_sql_data[tmd_k])
            tmd_mod_list.append(tmd_mog_data[tmd_k])
            tmd_x_list.append(str(tmd_k)+tmd_x_name)
    tmd_mod_sum = sum(tmd_mod_list)
    return tmd_x_list,tmd_mod_list,tmd_sql_list

@csrf_exempt
@login_required(login_url='/login')
def userchartThree(request):
    if request.is_ajax():
        if request.method == 'POST':
            jane_full_data('Two')
            uct_jane_id = cache.get('jane_id')
            new_jane_id = {v: k for k, v in uct_jane_id.items()}
            uct_user_device_sql = "SELECT tt.companyId, ( SELECT concat(factoryName, productId) FROM zy_device_model d WHERE tt.deviceModelId = d.deviceModelId ) AS devicesName, tt.num FROM (SELECT t.companyId, t.deviceModelId, COUNT(1) AS num FROM y_info_account a, (SELECT c.companyId, ssd.deviceModelId, b.accountId FROM s_shop c, c_account_shop b, s_shop_device ssd WHERE c.shopId = b.shopId AND c.isDelete = 0 AND c.shopState = 1 AND c.isUsing = 1 AND b.isDelete = 0 AND c.companyId NOT IN (0, 1, 2, 3, 4, 8) AND ssd.isDelete = 0 AND ssd.unLineDate IS NOT NULL AND ssd.deviceModelId IS NOT NULL AND c.shopId = ssd.shopId ) t WHERE t.accountId = a.accountId AND a.isDelete = 0 GROUP BY t.companyId, t.deviceModelId ) tt WHERE tt.num > 100 ORDER BY tt.num DESC"
            uct_user_device_data = mysqlcon.getAll(uct_user_device_sql)
            uct_device_list = []
            uct_company = []
            uct_user_data = {}
            for uct_i in uct_user_device_data:
                try:
                    jane_company = new_jane_id[uct_i[0]]
                    if jane_company not in uct_company or uct_i[1] not in uct_device_list:
                        if jane_company not in uct_company:
                            uct_company.append(jane_company)

                        if uct_i[1] not in uct_device_list:
                            uct_device_list.append(uct_i[1])

                        try:
                            uct_len_long = len(uct_company) - len(uct_user_data[uct_i[1]])
                            uct_o_data = [uct_x - uct_x for uct_x in range(uct_len_long-1)]
                            uct_o_data.append(uct_i[2])
                            for uct_o in uct_o_data:
                                uct_user_data[uct_i[1]].append(uct_o)
                            for uct_k,uct_v in uct_user_data.items():
                                if uct_k != uct_i[1]:
                                    uct_len_long = len(uct_company) - len(uct_v)
                                    for uct_r in range(uct_len_long):
                                        uct_user_data[uct_k].append(0)
                                    # print('==',uct_user_data)
                        except:
                            if uct_user_data != {}:
                                try:
                                    uct_len_long = len(uct_company) - len(uct_user_data[uct_i[1]])
                                    uct_o_data = [uct_x - uct_x for uct_x in range(uct_len_long)]
                                except:
                                    uct_len_long = len(uct_company)
                                    uct_o_data = [uct_x - uct_x for uct_x in range(uct_len_long-1)]
                                uct_o_data.append(uct_i[2])
                                uct_user_data[uct_i[1]] = uct_o_data
                            else:
                                uct_user_data[uct_i[1]] = [uct_i[2]]
                    else:
                        uct_list_id = uct_device_list.index(uct_i[1])
                        # print(uct_list_id)
                        uct_user_data[uct_i[1]][uct_list_id] = uct_user_data[uct_i[1]][uct_list_id] + uct_i[2]
                except KeyError:
                    pass
            for uct_k, uct_v in uct_user_data.items():
                uct_len_long = len(uct_company) - len(uct_v)
                for uct_r in range(uct_len_long):
                    uct_user_data[uct_k].append(0)
            return HttpResponse(json.dumps({'company_list': uct_company, 'device_list': uct_device_list, 'user_data':uct_user_data}))

@csrf_exempt
@login_required(login_url='/login')
def devicechartfour(request):
    if request.is_ajax():
        if request.method == 'POST':
            dcf_sql = "SELECT t.devicesName, SUM(t.num) AS devicesum FROM (SELECT c.companyId, ( SELECT concat(factoryName, productId) FROM zy_device_model d WHERE ssd.deviceModelId = d.deviceModelId ) AS devicesName, COUNT(1) AS num FROM s_shop c, s_shop_device ssd WHERE c.isDelete = 0 AND c.shopState = 1 AND c.isUsing = 1 AND c.companyId NOT IN (0, 1, 2, 3, 4, 8) AND ssd.isDelete = 0 AND ssd.unLineDate IS NOT NULL AND ssd.deviceModelId IS NOT NULL AND c.shopId = ssd.shopId GROUP BY c.companyId, ssd.deviceModelId ORDER BY COUNT(1) DESC ) t GROUP BY t.devicesName ORDER BY SUM(t.num) DESC"
            dcf_data = mysqlcon.getAll(dcf_sql)
            dcf_y_list = []
            dcf_value_list = []
            for dcf_i in dcf_data:
                dcf_y_list.append(dcf_i[0])
                dcf_value_list.append(int(dcf_i[1]))
            print(dcf_y_list)
            print(dcf_value_list)
            return HttpResponse(json.dumps({'y_list':dcf_y_list, 'value_list': dcf_value_list}))

@login_required(login_url='/login')
def usersum(request):
    # sum_user = []
    # global user_shop_return
    # global user_shop_excel
    # global user_shop_list
    # global sum_user_data
    # global alldate
    # obtain_data = obtain_user_shop()
    # u_newdate = datetime.now().strftime('%Y%m%d')
    # u_olddate = (datetime.now() + timedelta(days=-6)).strftime('%Y%m%d')
    # # print(u_newdate, u_olddate)
    # alldate = u_olddate + ' - ' + u_newdate
    # user_shop_return, user_shop_excel, user_shop_list = obtain_data.modify_data(u_olddate, u_newdate)
    # for u_k,u_v in user_shop_excel.items():
    #     sum_user.append(sum(u_v[4::2]))
    # sum_user_data = sum(sum_user)
    return render(request,'alldata/user-sum.html')


@csrf_exempt
@login_required(login_url='/login')
def usersum_send(request):
    sum_user=[]
    if request.is_ajax():
        if request.method == 'POST':
            global alldate
            global user_shop_return
            global user_shop_excel
            global user_shop_list
            global sum_user_data
            global alldate
            alldate = request.POST.get('date')
            old_date1 = datetime.strptime(alldate.split()[0], '%Y-%m-%d')
            new_date1 = datetime.strptime(alldate.split().pop(), '%Y-%m-%d')
            old_date2 = old_date1.strftime('%Y%m%d')
            new_date2 = new_date1.strftime('%Y%m%d')
            print('日期范围', old_date2, new_date2)
            obtain_data = obtain_user_shop()
            user_shop_return, user_shop_excel, user_shop_list  = obtain_data.modify_data(old_date2, new_date2)
            for u_k, u_v in user_shop_excel.items():
                print(u_v[5::2])
                sum_user.append(sum(u_v[5::2]))
            sum_user_data = sum(sum_user)
            return HttpResponse(json.dumps({"usersum_data_send": user_shop_return}))

@csrf_exempt
def usersum_select(request):
    new_user_shop_return = []
    if request.is_ajax():
        if request.method == 'POST':
            us_company = request.POST.get('companyname')
            if us_company == "":
                new_user_shop_return = user_shop_return
            else:
                pattern = re.compile(us_company)
                for us_i in user_shop_return:
                    results = pattern.findall(us_i['shop_name'])
                    if results != []:
                        new_user_shop_return.append(us_i)
            return HttpResponse(json.dumps({"usersum_data_send": new_user_shop_return}))

@csrf_exempt
@login_required(login_url='/login')
def other_user_data(request):
    global oud_data
    if request.is_ajax():
        if request.method == 'POST':
            oud_data_json = {}
            oud_data = obtain_data().mysql_con()
            oud_data_json["非安保用户"] = oud_data[0]["用户总量"] - sum_user_data
            oud_data.append(oud_data_json)
            return HttpResponse(json.dumps({"other_data_send": oud_data}))

@csrf_exempt
@login_required(login_url='/login')
def usersum_create(request):
    uc_title = str(alldate) + '用户汇总'
    shop_list_data = ["", "店铺总量", oud_data[0]["店铺总量"], "用户总量", oud_data[0]["用户总量"], "", "", "", "", "", "", "", "", ""]
    other_list_data = ["非安保APP用户", oud_data[2]["非安保用户"], "", "", "OBD用户", oud_data[1]['OBD用户'], "血压仪", "", "", "", "", "", "", ""]
    create_excel = create_user_excel()
    create_excel.generate_excel(uc_title, shop_list_data, other_list_data, user_shop_list, user_shop_excel)
    return HttpResponse(json.dumps({'status':0}))

@csrf_exempt
@login_required(login_url='/login')
def usersum_agg(request):
    agg_name = ['导入店铺汇总', '上线店铺汇总', '臻E盾用户汇总', '臻中心用户汇总', '臻护卫用户汇总', '臻总管用户汇总']
    agg_title = ['shop_dr', 'shop_on', 'user_ed', 'user_zx', 'user_hw', 'user_zg']
    agg_json = dict.fromkeys(agg_name, 0)
    agg_list = []
    if request.is_ajax():
        if request.method == 'POST':
            for ua_i in user_shop_return:
                for ua_n in range(len(agg_name)):
                    agg_json[agg_name[ua_n]] = agg_json[agg_name[ua_n]] + ua_i[agg_title[ua_n]]
            agg_list.append(agg_json)
            return HttpResponse(json.dumps({'agg_data':agg_list}))

@csrf_exempt
@login_required(login_url='/login')
def companynamesel(request):
    if request.is_ajax():
        if request.method == "POST":
            cns_data = jane_full_data('Three')
            print(cns_data)
            return HttpResponse(json.dumps({'no_jane_list': cns_data}))

@csrf_exempt
@login_required(login_url='/login')
def companynameadd(request):
    if request.is_ajax():
        if request.method == "POST":
            try:
                cna_fullname = request.POST.get('fullname')
                cna_janename = request.POST.get('janename')
                print(cna_fullname,cna_janename )
                c_company_jane.objects.create(full_name=cna_fullname, jane_name=cna_janename)
                cna_status = 0
            except:
                cna_status = 1
            return HttpResponse(json.dumps({'status':cna_status}))

@login_required(login_url='/login')
def infosum(request):
    enddate = datetime.now()
    startdate = enddate + timedelta(days=-6)
    info_return_list = infosel(startdate.strftime("%Y%m%d"),enddate.strftime("%Y%m%d"))
    return render(request,  'alldata/info-sum.html', {"info_return_list":info_return_list})

@csrf_exempt
@login_required(login_url='/login')
def infosum_send(request):
    if request.is_ajax():
        if request.method == "POST":
            _status = 1
            info_return_list = []
            try:
                i_date = request.POST.get("date")
                i_date_list = i_date.split(" - ")
                startdate = i_date_list[0].replace('-','')
                enddate = i_date_list[1].replace('-','')
                info_return_list = infosel(startdate, enddate)
                _status = 0
            except BaseException as b:
                _log_err = "infosum_send 函数报错 --》" + str(b)
                print(_log_err)
            finally:
                return HttpResponse(json.dumps({"status":_status, "info_return_list":info_return_list}))


@csrf_exempt
@login_required(login_url='/login')
def infoexcel(request):
    if request.is_ajax():
        if request.method == "POST":
            e_date = request.POST.get("datetime")
            c_info_e = create_info_excel()
            if e_date == "0":
                enddate = datetime.now()
                startdate = enddate + timedelta(days=-6)
                info_return_list = infosel(startdate.strftime("%Y%m%d"), enddate.strftime("%Y%m%d"))
                title = startdate.strftime("%Y%m%d") + "--" + enddate.strftime("%Y%m%d")
                c_info_e.generate_info_excel(title, info_return_list)
            else:
                i_date_list = e_date.split(" - ")
                startdate = i_date_list[0].replace('-', '')
                enddate = i_date_list[1].replace('-', '')
                info_return_list = infosel(startdate, enddate)
                title = startdate + "--"+ enddate
                c_info_e.generate_info_excel(title, info_return_list)
        return HttpResponse({"status":0})


infocon = InfoMysql()
def infosel(startdate, enddate):
    i_name_list = ['title', 'type', 'label_name', 'channel_name', 'real_hits', 'createDate']
    i_sql = """SELECT ei.title , ( SELECT ec.type_name FROM e_info_type_book ec WHERE ei.type_id = ec.type_id ) AS type, ei.label_name , ( SELECT eb.channel_name FROM e_info_channel_book eb WHERE eic.channel_id = eb.channel_id ) AS channel, ei.click_rate - ei.py_click_rate AS real_hits, ei.createDate FROM e_info ei LEFT JOIN e_info_channel eic ON ei.id = eic.info_id WHERE ei.isDeleted = 0 AND DATE_FORMAT(ei.createDate, '%Y%m%d') >= {0} AND DATE_FORMAT(ei.createDate, '%Y%m%d') <= {1} ORDER BY real_hits DESC""".format(startdate,enddate)
    i_return_data = infocon.getAll(i_sql)
    i_return_list = []
    for i_d in i_return_data:
        i_return_json = {}
        for i_n in range(len(i_name_list)):
            if i_name_list[i_n] == "createDate":
                i_return_json[i_name_list[i_n]] = i_d[i_n].strftime("%Y-%m-%d %H:%M:%S")
            elif i_name_list[i_n] == "real_hits" and i_d[i_n] == None:
                i_return_json[i_name_list[i_n]] = 0
            else:
                i_return_json[i_name_list[i_n]] = i_d[i_n]
        i_return_list.append(i_return_json)
    return i_return_list
